﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CDB.LinqData;
using CDB.LinqModel.Data;
using CDB.LinqModel;

public partial class back_AddBlog : System.Web.UI.Page
{
    #region Variable Declaration
    IDataRepository _dataObject = new DataRepository();
    Blog blog;
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (Session["admin"] != null)
            {
                if (Request.QueryString["Id"] != null)
                    bindBlog(Convert.ToString(Request.QueryString["Id"]));
            }
            else
                Response.Redirect("login.aspx");
        }
    }
    private void bindBlog(string blogId)
    {
        blog = new Blog(_dataObject);
        blog.Id = Convert.ToInt16(blogId);
        blog.GetBlogById();

        if (blog.Id != 0)
        {
            txtBlogName.Text = blog.Name;
            txtContent.InnerHtml = blog.Content;
        }
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        blog = new Blog(_dataObject);

        if (Request.QueryString["Id"] != null)
        {
            blog.Id = Convert.ToInt32(Request.QueryString["Id"].ToString());
            blog.Name = Convert.ToString(txtBlogName.Text.Trim());
            blog.Content = Convert.ToString(txtContent.InnerHtml.Trim());
            blog.Update();

            divMessage.InnerHtml = "<strong>Well done!</strong>&nbsp;Page updated successfully!";
            divMessage.Attributes.Add("class", "alert alert-success");
        }
        else
        {
            blog.Name = txtBlogName.Text.Trim();
            blog.GetContentByBlogName();

            if (blog.Id != 0)
            {
                divMessage.InnerHtml = "<strong>Oh snap!</strong>&nbsp;Blog with the same name exists!";
                divMessage.Attributes.Add("class", "alert alert-error");
            }
            else
            {
                blog.Name = Convert.ToString(txtBlogName.Text.Trim());
                blog.Content = Convert.ToString(txtContent.InnerHtml.Trim());
                blog.DateAdded = System.DateTime.Now;
                blog.Create();
                clearControls();
                divMessage.InnerHtml = "<strong>Well done!</strong>&nbsp;Blog added successfully!";
                divMessage.Attributes.Add("class", "alert alert-success");
            }
        }
    }
    private void clearControls()
    {
        txtBlogName.Text = string.Empty;
        txtContent.InnerText = string.Empty;
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("viewBlog.aspx");
    }
}